package com.probiz.estoresa.product.web.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;

import com.probiz.estore.Constants;
import com.probiz.estore.catalog.service.ProductCategoryManager;
import com.probiz.estore.common.helper.AttributeUtil;
import com.probiz.estore.common.helper.ConfigUtil;
import com.probiz.estore.common.model.attribute.AttributeValue;
import com.probiz.estore.common.model.catalog.ProductCategory;
import com.probiz.estore.common.model.other.Tag;
import com.probiz.estore.common.model.product.Brand;
import com.probiz.estore.common.model.product.Product;
import com.probiz.estore.common.model.product.ProductSkuOptionValue;
import com.probiz.estore.common.model.product.ProductType;
import com.probiz.estore.common.model.product.ProductTypeBrand;
import com.probiz.estore.common.model.product.ProductTypeSkuOption;
import com.probiz.estore.common.model.product.SkuOption;
import com.probiz.estore.common.model.product.SkuOptionValue;
import com.probiz.estore.common.model.sales.RecommendedType;
import com.probiz.estore.core.controller.GenericStoreAdminController;
import com.probiz.estore.core.exception.ApplicationException;
import com.probiz.estore.core.model.BaseObject;
import com.probiz.estore.core.search.SearchCriteria;
import com.probiz.estore.core.view.DownloadView;
import com.probiz.estore.other.service.TagManager;
import com.probiz.estore.product.model.ProductFullyModel;
import com.probiz.estore.product.model.ProductSearchCriteria;
import com.probiz.estore.product.model.ProductUniBulkEditModel;
import com.probiz.estore.product.service.BrandManager;
import com.probiz.estore.product.service.ProdMainManager;
import com.probiz.estore.product.service.ProductManager;
import com.probiz.estore.product.service.ProductTypeManager;
import com.probiz.estore.product.service.SkuOptionValueManager;
import com.probiz.estore.sales.model.RecommendedTypeSearchCriteria;
import com.probiz.estore.sales.service.AutoEvalRecommendationManager;
import com.probiz.estore.sales.service.RecommendedTypeManager;
import com.probiz.estore.webapp.util.RequestUtil;

public class ProductController extends GenericStoreAdminController<Product> {
	private ProdMainManager prodMainManager = null;
	private ProductManager productManager = null;
	private ProductCategoryManager productCategoryManager = null;
	private BrandManager brandManager = null;
	private ProductTypeManager productTypeManager = null;
	private SkuOptionValueManager skuOptionValueManager = null;
	private RecommendedTypeManager recommendedTypeManager = null;
	private AutoEvalRecommendationManager autoEvalRecommendationManager = null;
	private TagManager tagManager = null;

	public void setProdMainManager(ProdMainManager prodMainManager) {
		this.prodMainManager = prodMainManager;
	}

	public void setProductManager(ProductManager inMgr) {
		this.productManager = inMgr;
	}


	public void setProductCategoryManager(
			ProductCategoryManager productCategoryManager) {
		this.productCategoryManager = productCategoryManager;
	}
	

	public void setBrandManager(BrandManager brandManager) {
		this.brandManager = brandManager;
	}

	public void setProductTypeManager(ProductTypeManager productTypeManager) {
		this.productTypeManager = productTypeManager;
	}
	

	public void setSkuOptionValueManager(SkuOptionValueManager skuOptionValueManager) {
		this.skuOptionValueManager = skuOptionValueManager;
	}

	public void setRecommendedTypeManager(
			RecommendedTypeManager recommendedTypeManager) {
		this.recommendedTypeManager = recommendedTypeManager;
	}
	
	

	public void setAutoEvalRecommendationManager(
			AutoEvalRecommendationManager autoEvalRecommendationManager) {
		this.autoEvalRecommendationManager = autoEvalRecommendationManager;
	}
	
	

	
	public void setTagManager(TagManager tagManager) {
		this.tagManager = tagManager;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.core.controller.GenericController#getEntityName(java.lang.Object)
	 */
	@Override
	protected String getEntityName(Product entity) {
		return entity.getProductName();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.core.controller.BaseController#initController()
	 */
	@Override
	protected void initController() throws Exception {
		mgr = productManager;
	}

	public ModelAndView defaultAction(HttpServletRequest request,
			HttpServletResponse response) {
		ModelAndView mv = new ModelAndView("product/productList");

		ProductCategory treeRoot = productCategoryManager.getById(1);
		Set<ProductCategory> categorySet = treeRoot.getChildren();
		List<ProductCategory> categoryList = new ArrayList<ProductCategory>();
		categoryList.addAll(categorySet);
		mv.addObject("categoryList", categoryList);
		mv.addObject("treeRoot", treeRoot);
		mv.addObject("productTypeList",productTypeManager.listAll());
		mv.addObject("brandList", brandManager.listAll());
		
		return mv;
	}
	
	
	

	/**
	 * 重载edit方法，主要是去掉设置导航信息,否则列表页面跳转会有问题，（savedNavAndSearchCriteria(....)），其他处理与框架一致，
	 */
	@Override
	public ModelAndView edit(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView(formView);
		Product product = formBackingObject(request);
		//start:商品种类
		if(product.getProductKind() == null){
			if(RequestUtil.getParameterNullSafe(request, "package").equals("true")){
				product.setProductKind(Product.PRODUCTKIND_PACKAGE);
			}else{
				product.setProductKind(Product.PRODUCTKIND_PRODUCT);
				
			}
		}	
		//end:商品种类
		
		//start: 商品类型
		String productTypeId = RequestUtil.getParameterNullSafe(request,
				"productTypeId");
		ProductType productType = null;
		if (StringUtils.isNotBlank(productTypeId)) {
			productType = productTypeManager.getById(Integer.parseInt(productTypeId));
			product.setProductType(productType);
		}
		request.setAttribute("productType", product.getProductType());
		//end: 商品类型
		
		//start:商品目录
		if(StringUtils.isNotBlank(RequestUtil.getParameterNullSafe(request, "productCategoryId"))){
			product.setCategory(productCategoryManager.getById(Integer.valueOf(RequestUtil.getParameterNullSafe(request, "productCategoryId"))));
		}
		//end:商品目录
		
		//start:品牌列表
		if(product.getProductType() != null){
			List<Brand> brandList = new ArrayList<Brand>();
			for(ProductTypeBrand productTypeBrand: product.getProductType().getProductTypeBrands()){
				brandList.add(productTypeBrand.getBrand());
			}
			if (null != product.getBrand() && !brandList.contains(product.getBrand())) {
				brandList.add(product.getBrand());
			}
			mv.addObject("brandList",brandList);
		}else{
			mv.addObject("brandList",brandManager.listAll());
		}
		//end:品牌列表
		
		
		mv.addObject("product",product);
		mv.addObject("weightUnit",ConfigUtil.getInstance().getWeightUnit());
		return mv;
	}
	/**
	 * 加载图片区域
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView loadAreaOfImages(HttpServletRequest request,HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("product/include/productFormImages");
		Product product = formBackingObject(request);
		mv.addObject("product",product);
		return mv;
	}
	/**
	 * 加载货品区域
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView loadAreaOfSkus(HttpServletRequest request,HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("product/include/productFormSkus");
		Product product = formBackingObject(request);
		mv.addObject("product",product);
		
		//start: 商品类型
		String productTypeId = RequestUtil.getParameterNullSafe(request,
				"productTypeId");
		ProductType productType = null;
		if (StringUtils.isNotBlank(productTypeId)) {
			productType = productTypeManager.getById(Integer.parseInt(productTypeId));
			product.setProductType(productType);
		}
		request.setAttribute("productType", product.getProductType());
		//end: 商品类型
		
		//start:规格列表
		List<SkuOption> skuOptionList = new ArrayList<SkuOption>();
		for(ProductTypeSkuOption productTypeSkuOption:product.getProductType().getProductTypeSkuOptions()){
			skuOptionList.add(productTypeSkuOption.getSkuOption());
		}
		mv.addObject("skuOptionList",skuOptionList);
		//end:规格列表
		
		
		//用于页面判断规格 optionIds 存放商品的规格id字符串拼接,形如 ,1,2,  ,2,4,5,
		StringBuffer optionIds = new StringBuffer();
		optionIds.append(",");
		if(null != product.getDefaultProductSku()){
			for(ProductSkuOptionValue relation : product.getDefaultProductSku().getProductSkuOptionValues()){
				SkuOptionValue option = skuOptionValueManager.getById(relation.getSkuOptionValueId());
				optionIds.append(option.getSkuOptionId()).append(",");
			}
		}	
		mv.addObject("optionIds", optionIds);
		
		return mv;
	}
	
	/**
	 * 加载属性区域
	 * @deprecated 图片类的商品属性无法在使用tab的情况下ajax load
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 * 
	 */
	public ModelAndView loadAreaOfAttributes(HttpServletRequest request,HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("product/include/productFormAttributes");
		Product product = formBackingObject(request);
		mv.addObject("product",product);
		
		//start: 商品类型
		String productTypeId = RequestUtil.getParameterNullSafe(request,
				"productTypeId");
		ProductType productType = null;
		if (StringUtils.isNotBlank(productTypeId)) {
			productType = productTypeManager.getById(Integer.parseInt(productTypeId));
			product.setProductType(productType);
		}
		request.setAttribute("productType", product.getProductType());
		//end: 商品类型
		return mv;
	}
	
	/**
	 * 加载关联推荐区域
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView loadAreaOfRecommended(HttpServletRequest request,HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("product/include/productFormRecommended");
		Product product = formBackingObject(request);
		mv.addObject("product",product);
		
		//start:激活的关联推荐类型
		RecommendedTypeSearchCriteria recommendedTypeSearchCriteria = new RecommendedTypeSearchCriteria();
		recommendedTypeSearchCriteria.setStatus(Constants.FLAG_TRUE);
		recommendedTypeSearchCriteria.setIsApplyToProduct(Constants.FLAG_TRUE);
		List<RecommendedType> recommendedTypeList = recommendedTypeManager.getRecommendedTypesBySearchCriteria(recommendedTypeSearchCriteria);
		mv.addObject("recommendedTypeList", recommendedTypeList);
		//end:激活的关联推荐类型
		return mv;
	}
	
	protected void onShowForm(HttpServletRequest request, ModelAndView mv){
		
		
	}
	
	/**
	 * 获得自动评估商品列表
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView getAutoEvalProducts(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		Map<String, Object> data = new HashMap<String, Object>();
		Integer productId = RequestUtil.getInteger(request, "productId");
		Integer recommendedTypeId = RequestUtil.getInteger(request, "recommendedTypeId");
		RecommendedType recommendedType = recommendedTypeManager.getById(recommendedTypeId);
		List<Product> result = autoEvalRecommendationManager.getProductsByRuleCodeBySourceId(recommendedType.getRuleCode(), productId, 0, 8);
		JSONArray autoEvalProductArray = new JSONArray();
		for(Product product: result){
			JSONObject jsonProduct = new JSONObject();
			jsonProduct.put("id", product.getProductId());
			jsonProduct.put("name", product.getProductName());
			jsonProduct.put("imageUrl", product.getImageUrl());
			autoEvalProductArray.add(jsonProduct);
		}
		data.put("autoEvalProductArray", autoEvalProductArray);
		data.put("recommendedTypeId", recommendedTypeId);
		return getModelAndAjaxJsonView(data);
	}

	/**
	 * 重载add方法，主要是去掉设置导航信息,否则列表页面跳转会有问题，（savedNavAndSearchCriteria(....)），其他处理与框架一致，
	 */
	public ModelAndView add(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		return selectProductType(request,response);
	}
	/**
	 * 选择类型
	 */
	public ModelAndView selectProductType(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Product entity = formBackingObject(request);
		ModelAndView mv = new ModelAndView("product/productFormSelectType");
		SearchCriteria sc = productTypeManager.getSearchCriteriaBuilder(BaseObject.FilterHqlName.DEFAULT).buildSearchCriteria(request, (RequestUtil.getInteger(request, "PrmItemsPerPage")!=null)?(RequestUtil.getInteger(request, "PrmItemsPerPage")):defaultPageSize);
		request.setAttribute("sc", sc);
		mv.addObject("productTypeList", productTypeManager.searchByCriteria(sc));
		request.setAttribute("productCategoryId", request.getParameter("productCategoryId"));//将选中的目录id继续传递
		return mv;
	}
	
	

	public ModelAndView search(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mv = new ModelAndView("product/include/productListBody");
		SearchCriteria searchCriteria = createSearchCriteria(request);
		ProductSearchCriteria productSearchCriteria = new ProductSearchCriteria();
		try {
			// 绑定参数
			bind(request, productSearchCriteria);
			List<Product> productList = productManager.searchByCriteriaForController(productSearchCriteria, searchCriteria);
			mv.addObject("productList", productList);
			mv.addObject("productSearchCriteria", productSearchCriteria);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return mv;
	}

	public ModelAndView delete(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String entityId = request.getParameter(entityIdName);
		Product product = productManager.getById(Integer.valueOf(entityId));
		short deleteStatus = prodMainManager.deleteFully(product);
		
		Map<String, Object> data = new HashMap<String, Object>();
		JSONArray jsonArray = new JSONArray();
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("productName", product.getProductName());
		jsonObject.put("deleteStatus", deleteStatus);
		jsonArray.add(jsonObject);
		data.put("deleteInfos", jsonArray);
		JSONObject jsonMap = JSONObject.fromObject(data);
		PrintWriter out = response.getWriter();
		out.println(jsonMap.toString());
		return null;
	}
	
	public ModelAndView checkSkuIsInUse(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Integer productSkuId = RequestUtil.getInteger(request, "productSkuId");
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("result", prodMainManager.checkSkuIsInUse(productSkuId));
		data.put("productSkuId", productSkuId);
		JSONObject jsonMap = JSONObject.fromObject(data);
		PrintWriter out = response.getWriter();
		out.println(jsonMap.toString());
		return null;
	}

	public ModelAndView multiDelete(HttpServletRequest request,
			HttpServletResponse response) {
		// 取得要删除的记录的id的列表。注意：选择框的id要是"multiIds"。
		String[] ids = request.getParameterValues("multiIds");
		Map<String, Object> data = new HashMap<String, Object>();
		JSONArray jsonArray = new JSONArray();
		
		if (ids != null && ids.length > 0) {
			for (String entityId : ids) {
				Product product = productManager.getById(Integer.valueOf(entityId));
				short deleteStatus = prodMainManager.deleteFully(product);
				JSONObject jsonObject = new JSONObject();
				jsonObject.put("productName", product.getProductName());
				jsonObject.put("deleteStatus", deleteStatus);
				jsonArray.add(jsonObject);
			}
		}
		data.put("deleteInfos", jsonArray);
		JSONObject jsonMap = JSONObject.fromObject(data);
		PrintWriter out;
		try {
			out = response.getWriter();
			out.println(jsonMap.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/*
	 * 保存前的检验和赋值.
	 */
	protected void preSave(HttpServletRequest request, Product entity,
			BindException errors) {
		// start:赋值dispalyFlag
		String[] displayFlagArray = RequestUtil.getParameterValuesNullSafe(
				request, "displayFlag");
		StringBuffer displayFlag = new StringBuffer();
		for (String flag : displayFlagArray) {
			displayFlag.append(flag);
		}
		entity.setDisplayFlag(displayFlag.toString());
		// end:赋值dispalyFlag

	}

	public ModelAndView save(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// 取得Form对应的Model
		Product entity = formBackingObject(request);
		BindException errors = null;
		Map<String, Object> data = new HashMap<String, Object>();
		try {
			bindReady(entity);
			ServletRequestDataBinder binder = bindAndValidate(request, entity);
			errors = new BindException(binder.getBindingResult());
			// 传给子类的实现，后者可以继续验证和加入错误到errors
			preSave(request, entity, errors);
			if (!errors.hasErrors()) {// 里面如果出错应该抛出异常
				ProductFullyModel productFullyModel = getProductFullyModel(request, entity, data);
				Map<String, Object> saveData = prodMainManager
						.saveFully(productFullyModel);
				data.putAll(saveData);
			}
		} catch (ApplicationException e) {
			e.printStackTrace();
			handleApplicationException(errors, e);
			data.put("error", e.getMessage());
		} catch(Exception e){
			e.printStackTrace();
			data.put("error", e.getMessage());
		}

		buildReturnInfo(data, entity, request);

		return getModelAndAjaxJsonView(data);
	}

	// 加入返回参数
	private void buildReturnInfo(Map<String, Object> data, Product product,
			HttpServletRequest request) {
		data.put("productId", product.getProductId());
		data.put("productName", product.getProductName());
		data.put("productCode", product.getProductCode());
		data.put("status", product.getStatus());
		
	

	}

	// 保存前的绑定
	private void bindReady(Product entity) {
		if (null == entity.getProductId()) {
			// case:新增

		}
		
	}

	// 构造产品模型，方便保存
	private ProductFullyModel getProductFullyModel(HttpServletRequest request,
			Product product, Map<String, Object> data) {
		ProductFullyModel model = new ProductFullyModel();
	
		model.setProduct(product);
		
		// ---------- start: 绑定描述 ------------
		model.setShortDescription(RequestUtil.getParameterNullSafe(request,
				"shortDescription"));
		model.setDescription(RequestUtil.getParameterNullSafe(request,
				"description"));

		// ---------- end:绑定描述 ---------------

		// ---------- start:绑定媒体--------------
		String[] mediaIds = (String[]) ArrayUtils.clone(RequestUtil
				.getParameterValuesNullSafe(request, "mediaIds"));
		String[] mediaUrls = RequestUtil.getParameterValuesNullSafe(request,
				"mediaUrls");
		String[] mediaTypes = RequestUtil.getParameterValuesNullSafe(request,
				"mediaTypes");
		String[] mediaDescs = RequestUtil.getParameterValuesNullSafe(request,
				"mediaDescs");
		// 清理空的数据begin
		for (int i = 0; i < mediaIds.length; i++) {
			if (StringUtils.isEmpty(mediaUrls[i])) {
				mediaIds = (String[]) ArrayUtils.remove(mediaIds, i);
				mediaUrls = (String[]) ArrayUtils.remove(mediaUrls, i);
				mediaTypes = (String[]) ArrayUtils.remove(mediaTypes, i);
				mediaDescs = (String[]) ArrayUtils.remove(mediaDescs, i);
				i--; // 因为已经移除了一个元素，所以必须将游标-1，否则会跳过一个元素
			}
		}
		// 清理空的数据end
		// 传入返回map
		data.put("oldMediaIds", mediaIds);
		String[] newOrUpdatemediaIds = (String[]) ArrayUtils.clone(mediaIds);// 这里复制是为了可以在不改变request中的数据
		for (int i = 0; i < newOrUpdatemediaIds.length; i++) {
			if (newOrUpdatemediaIds[i].contains("new")) {
				// case:媒体是新增的
				newOrUpdatemediaIds[i] = "";
			} else {
				// case:媒体已存在
				newOrUpdatemediaIds[i] = mediaIds[i].substring(mediaIds[i]
						.indexOf("_") + 1);
			}
		}
		model.setMediaIds(newOrUpdatemediaIds);
		model.setMediaUrls(mediaUrls);
		model.setMediaTypes(mediaTypes);
		model.setMediaDescs(mediaDescs);
		// --------- end:绑定媒体----------------

		// --------- start: 绑定SKU----------------
		String[] skuIds = (String[]) ArrayUtils.clone(RequestUtil
				.getParameterValuesNullSafe(request, "skuIds"));
		String[] skuCodes = RequestUtil.getParameterValuesNullSafe(request,
				"skuCodes");
		String[] skuImageUrls = RequestUtil.getParameterValuesNullSafe(request,
				"skuImageUrls");
		String[] listPrices = RequestUtil.getParameterValuesNullSafe(request,
		"listPrices");
		String[] prices = RequestUtil.getParameterValuesNullSafe(request,
		"prices");
		String[] salePrices = RequestUtil.getParameterValuesNullSafe(request,
		"salePrices");
		String[] weights = RequestUtil.getParameterValuesNullSafe(request,
		"weights");
		String[] inventorys = RequestUtil.getParameterValuesNullSafe(request,
		"inventorys");
		

		// 传入返回map
		data.put("oldSkuIds", skuIds);
		model.setOldSkuIds(skuIds);
		String[] newSkuIds = (String[]) ArrayUtils.clone(skuIds);// 这里复制是为了可以在不改变request中的数据
		for (int i = 0; i < newSkuIds.length; i++) {
			if (newSkuIds[i].contains("new")) {
				// case:sku是新增的
				newSkuIds[i] = "";
			} else {
				// case:sku已存在
				newSkuIds[i] = newSkuIds[i]
						.substring(newSkuIds[i].indexOf("_") + 1);
			}
		}
		model.setSkuIds(newSkuIds);
		model.setSkuCodes(skuCodes);
		model.setSkuImageUrls(skuImageUrls);
		model.setListPrices(listPrices);
		model.setPrices(prices);
		model.setSalePrices(salePrices);
		model.setWeights(weights);
		model.setInventorys(inventorys);
		// --------- end: 绑定SKU----------------

		// --------- start: 绑定wholesalePrice----------------
		String[] wpIds = (String[]) ArrayUtils.clone(RequestUtil
				.getParameterValuesNullSafe(request, "wpIds"));
		String[] wpMinQuantitys = RequestUtil.getParameterValuesNullSafe(
				request, "wpMinQuantitys");
		String[] wpMaxQuantitys = RequestUtil.getParameterValuesNullSafe(
				request, "wpMaxQuantitys");
		String[] wpPrices = RequestUtil.getParameterValuesNullSafe(request,
				"wpPrices");
		String[] wpDeliveryDays = RequestUtil.getParameterValuesNullSafe(
				request, "wpDeliveryDays");
		String[] wpSkuIds = RequestUtil.getParameterValuesNullSafe(request,
				"wpSkuIds");

		// 传入返回map
		data.put("oldWpIds", wpIds);
		data.put("oldWpSkuIds", wpSkuIds);
		model.setOldWpSkuIds(wpSkuIds);
		String[] newWpIds = (String[]) ArrayUtils.clone(wpIds);// 这里复制是为了可以在不改变request中的数据
		for (int i = 0; i < newWpIds.length; i++) {
			if (newWpIds[i].contains("new")) {
				// case:sku是新增的
				newWpIds[i] = "";
			} else {
				// case:sku已存在
				newWpIds[i] = newWpIds[i]
						.substring(newWpIds[i].indexOf("_") + 1);
			}
		}
		model.setWpIds(newWpIds);
		model.setWpMinQuantitys(wpMinQuantitys);
		model.setWpMaxQuantitys(wpMaxQuantitys);
		model.setWpPrices(wpPrices);
		model.setWpDeliveryDays(wpDeliveryDays);
		// --------- end: 绑定wholesalePrice----------------

		// --------- start: 绑定产品属性----------------
		List<AttributeValue> attributeValues = AttributeUtil.getInstance()
				.getAttributeFromRequest(request);
		model.setAttributeValues(attributeValues);
		// --------- end: 绑定产品属性----------------
		
		
		// --------- start: 绑定商品规格----------------
		String[] selectedOptions = RequestUtil.getParameterValuesNullSafe(request, "selectedOptions");
		List<String[]> selectedOptionValuesList = new ArrayList<String[]>();
		for(String selectedOption : selectedOptions){
			String[] selectedOptionValues = RequestUtil.getParameterValuesNullSafe(request, "skuOption"+selectedOption);
			selectedOptionValuesList.add(selectedOptionValues);
			
		}
		model.setSkuOptionIds(selectedOptions);
		model.setSkuOptionValueIdsList(selectedOptionValuesList);
		// --------- end: 绑定商品规格----------------
		
		// --------- start: 绑定推荐关联商品----------------
		String[] recommendedTypeIds = RequestUtil.getParameterValuesNullSafe(request, "recommendedTypeIds");
		String[] recommendedProductIds = RequestUtil.getParameterValuesNullSafe(request, "recommendedProductIds");
		model.setRecommendedTypeIds(recommendedTypeIds);
		model.setRecommendedProductIds(recommendedProductIds);
		// --------- end: 绑定推荐关联商品----------------
		
		
		// --------- start: 绑定多个商品id 用于分别调价----------------
		model.setProductIds(RequestUtil.getParameterValuesNullSafe(request, "productIds"));
		// --------- end: 绑定多个商品id 用于分别调价----------------

		// --------- start: 绑定商品包----------------
		model.setItemSkuIds(RequestUtil.getIntegerArrayNullSafe(request, "itemSkuIds"));
		model.setItemQuantitys(RequestUtil.getIntegerArrayNullSafe(request, "itemQuantitys"));
		// --------- end: 绑定商品包----------------


		
		return model;

	}

	// start:产品上架
	public ModelAndView shelve(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Product product = formBackingObject(request);
		prodMainManager.doShelve(product);

		Map<String, Object> data = new HashMap<String, Object>();
		buildReturnInfo(data, product, request);
		return getModelAndAjaxJsonView(data);
	}

	public ModelAndView multiShelve(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String[] ids = request.getParameterValues("multiIds");
		if (ids != null && ids.length > 0) {
			for (String entityId : ids) {
				prodMainManager.doShelve(Integer.valueOf(entityId));
			}
		}
		return null;
	}

	// end:产品上架

	// start:产品下架
	public ModelAndView offShelve(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Product product = formBackingObject(request);
		prodMainManager.doOffShelve(product);
		Map<String, Object> data = new HashMap<String, Object>();
		buildReturnInfo(data, product, request);
		JSONObject jsonMap = JSONObject.fromObject(data);
		PrintWriter out = response.getWriter();
		out.println(jsonMap.toString());
		return null;
	}

	public ModelAndView multiOffShelve(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String[] ids = request.getParameterValues("multiIds");
		if (ids != null && ids.length > 0) {
			for (String entityId : ids) {
				prodMainManager.doOffShelve(Integer.valueOf(entityId));
			}
		}
		return null;
	}

	// end:产品下架
	
	// 用于判断商品是否可修改
	private boolean IsBulkEditAvailable(Product product) {
		if (Product.STATUS_ACTIVE.equals(product.getStatus())|| Product.STATUS_NOTACTIVE.equals(product.getStatus()))
			return true;
		return false;
	}

	/**
	 * 统一批修改頁面显示
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView unitiveBulkEdit(HttpServletRequest request,	HttpServletResponse response) throws Exception {
		String productIdsString = RequestUtil.getParameterNullSafe(request,"productIds");
		String[] productIds = productIdsString.split(",");
		List<Product> productList = new ArrayList<Product>();
		for (String productId : productIds) {
			Product product = productManager.getById(Integer.parseInt(productId));
			if (IsBulkEditAvailable(product)) {
				productList.add(product);
			}
		}
		ModelAndView mv = new ModelAndView("product/unitiveBulkEditForm");
		mv.addObject("brandList", brandManager.listAll());
		mv.addObject("productList", productList);
		return mv;
	}
	
	/**
	 * 统一批修改頁面保存
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView unitiveBulkEditSave(HttpServletRequest request,		HttpServletResponse response) throws Exception {
		Map<String, Object> data = new HashMap<String, Object>();
		ProductUniBulkEditModel model = new ProductUniBulkEditModel();
		bind(request,model);
		Map<String,Object> returnMsgs = prodMainManager.doUniBulkEdit(model);
		
		data.putAll(returnMsgs);
		data.put("result", "1");
		return getModelAndAjaxJsonView(data);
	}	
	
	
	/**
	 * 联合批修改頁面显示
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView associatedBulkEdit(HttpServletRequest request,	HttpServletResponse response) throws Exception {
		String productIdsString = RequestUtil.getParameterNullSafe(request,"productIds");
		String[] productIds = productIdsString.split(",");
		List<Product> productList = new ArrayList<Product>();
		for (String productId : productIds) {
			Product product = productManager.getById(Integer.parseInt(productId));
			if (IsBulkEditAvailable(product)) {
				productList.add(product);
			}
		}
		ModelAndView mv = new ModelAndView("product/associatedBulkEditForm");
		mv.addObject("productList", productList);
		return mv;
		
	}
	
	/**
	 * 联合批修改頁面保存
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView associatedBulkEditSave(HttpServletRequest request,	HttpServletResponse response) throws Exception {
		Map<String, Object> data = new HashMap<String, Object>();
		ProductFullyModel productFullyModel = getProductFullyModel(request, null, data);
		Map<String, Object> returnMsgs = prodMainManager.doAssBulkEdit(productFullyModel);
		data.putAll(returnMsgs);
		data.put("result", "1");
		return getModelAndAjaxJsonView(data);
	}
	/**
	 * 根据目录id获得路径全名
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView getFullCategoryPathName(HttpServletRequest request,	HttpServletResponse response) throws Exception {
		Map<String, Object> data = new HashMap<String, Object>();
		ProductCategory productCategory =productCategoryManager.getById(RequestUtil.getInteger(request, "categoryId"));
		data.put("fullCategoryPathName", productCategory.getFullCategoryPathName());
		return getModelAndAjaxJsonView(data);
	}
	/**
	 * 应用标签
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView applyTags(HttpServletRequest request,	HttpServletResponse response) throws Exception {
		Map<String, Object> data = null;
		String tagNames = RequestUtil.getParameterNullSafe(request, "tagNames");
		String[] ids = request.getParameterValues("multiIds");
		if (ids != null && ids.length > 0) {
			for (String entityId : ids) {
				Product product = productManager.getById(Integer.valueOf(entityId));
				data = tagManager.doSetTagField(product, Tag.MODULE_PRODUCT, tagNames);
				productManager.save(product);
			}
		}
		return getModelAndAjaxJsonView(data);
	}
	/**
	 * 详细页展开
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView showProductItem(HttpServletRequest request,	HttpServletResponse response) throws Exception {
		Product product = productManager.getById(RequestUtil.getInteger(request, "productId"));
		ModelAndView mv = new ModelAndView("product/include/productItemInList");
		mv.addObject("product", product);
		return mv;
		
	}
	
	
	/**
	 * 下载附件
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 */
	public ModelAndView downloadFile(HttpServletRequest request,HttpServletResponse response) throws ServletException {
        String path = ConfigUtil.getInstance().getMediaStorePath(request.getParameter("mediaUrl"));
		ModelAndView mv = new ModelAndView(new DownloadView(path));
        return mv;
               
	}
	
	
	
	
}
